package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "公共接口")
public class CommonContorller {

    /*
    * 新增菜品
    * */
    @Autowired
    private AliOssUtil aliOssUtil;
    @ApiOperation("图片上传")
    @PostMapping("/upload")
    public Result<String> savaImage( MultipartFile file) throws FileUploadException {
        log.info("文件上传:{}",file.getOriginalFilename());
        byte[] bytes;
        try {
            //文件二进制数据
            bytes = file.getBytes();
            //生成随机文件名+原文件后缀
            int index = file.getOriginalFilename().lastIndexOf(".");
            String fileName = UUID.randomUUID() + file.getOriginalFilename().substring(index);
            //上传后返回路径
            String filePath = aliOssUtil.upload(bytes, fileName);
            return Result.success(filePath);
        } catch (IOException e) {
            throw new FileUploadException(MessageConstant.UPLOAD_FAILED);
        }
    }
}
